#![windows_subsystem = "windows"]    // hide console window on Windows in release
// #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]    // show debug console window on Windows in release
use slint::SharedPixelBuffer;
use plotters::prelude::*;

slint::include_modules!();


fn sin_wave(freq: f32, amp: f32, phase: f32, offset: f32, sample_rate: f32, duration: f32, vscale: (f32,f32)) -> Vec<(f32, f32)> {
    let num_points:u64 = (duration * sample_rate) as u64;
    (0..num_points).map(|i| {
        let time = i as f32 / sample_rate;
        (vscale.0*time, vscale.1*amp * (freq * time * std::f32::consts::PI * 2.0 + phase).sin())
    }).collect::<Vec<_>>()
}

fn get_svgcmd(points: &Vec<(f64, f64)>) -> String {
    let mut svgcmd = String::from("M");
    let first_point = points[0];
    // dbg!(&points);
    svgcmd += &format!(" {} {}", first_point.0, first_point.1);
    for (x, y) in points[1..].iter() {
        svgcmd += &format!(" L {} {}", x.round() as i64, y.round() as i64);
    }
    // dbg!(&svgcmd);
    svgcmd
}

fn render_plot(freq: f32, amp: f32, phase: f32, offset: f32) -> slint::Image {
    let mut pixel_buffer = SharedPixelBuffer::new(640, 480);
    let size = (pixel_buffer.width(), pixel_buffer.height());

    let backend = BitMapBackend::with_buffer(pixel_buffer.make_mut_bytes(), size);

    let root = backend.into_drawing_area();
    root.fill(&WHITE).expect("error filling drawing area");

    let mut chart = ChartBuilder::on(&root)
        .caption("y=Amp*sin(2*pi*freq*t + phase) + offset", ("sans-serif", 10).into_font())
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(30)
        .build_cartesian_2d(0f32..1f32, (-1.2*amp+offset)..(1.2*amp+offset)).unwrap();

    chart.configure_mesh().draw().expect("error drawing");

    chart.draw_series(
            LineSeries::new(
                // sin_wave(freq, amp, phase, offset, 10.0, 0.01,(1.0, 1.0)),
                (0..=10000).map(|x| x as f32 / 10000.0).map(|x| (x, amp * (freq * x * std::f32::consts::PI * 2.0 + phase/360.0).sin()+offset)),
                &RED,
            )).unwrap()
            .label("y=Amp*sin(2*pi*freq*t + phase) + offset")
            .legend(|(x, y)| PathElement::new([(x, y), (x + 20, y)], &RED));
    chart.configure_series_labels()
        .background_style(&WHITE.mix(0.8))
        .border_style(&BLACK)
        .draw().unwrap();

    root.present().expect("error presenting");
    drop(chart);
    drop(root);

    slint::Image::from_rgb8(pixel_buffer)
}




fn main() {
    let ui = MainWindow::new().unwrap();
    let ui_weak = ui.as_weak();
    ui.global::<GlobalVariables>().on_sendcmd(move |cmd| {
        let ui = ui_weak.unwrap();
        let logrecord = ui.global::<GlobalVariables>().get_logstring();
        let logrecord = logrecord + "\n" + &cmd;
        ui.global::<GlobalVariables>().set_logstring(logrecord);
    });
    ui.run().unwrap();
}
